package com.seedwill.common.converter;

import java.sql.Clob;
import java.sql.SQLException;

import org.apache.commons.beanutils.ConversionException;
import org.apache.commons.beanutils.Converter;

public class StringConverter implements Converter {

	public static String valueOf(Object value) {
		if (value == null) {
			return null;
		}
		if (value instanceof String) {
			return (String)value;
		}
		Class type = value.getClass();
		if (type == byte[].class) {
			byte[] valueArray = (byte[]) value;
			return new String(valueArray, 0, valueArray.length);
		}
		if (value instanceof Clob) {
			Clob clob = (Clob) value;
			try {
				long lenght = clob.length();
				if (lenght > Integer.MAX_VALUE) {
					throw new ConversionException("Clob is too big.");
				}
				return clob.getSubString(1, (int) lenght);
			} catch (SQLException sex) {
				throw new ConversionException(sex);
			}
		}
		return value.toString();
	}

	public Object convert(Class type, Object value) {
		return valueOf(value);
	}

}
